import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import PrintView from '../views/PrintView.vue'
import ControlView from '../views/ControlView.vue'
import { useUserStore } from '../stores/user'
import { storeToRefs } from 'pinia'

const routes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView,
  },
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true },
  },
  {
    path: '/print',
    name: 'print',
    component: PrintView,
    meta: { requiresAuth: true },
  },
  {
    path: '/control',
    name: 'control',
    component: ControlView,
    meta: { requiresAuth: true },
  },
  {
    path: '/:catchAll(.*)',
    redirect: '/login',
  },
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

router.beforeEach((to, from, next) => {
  const userStore = useUserStore()
  const { username } = storeToRefs(userStore)
  if (to.meta.requiresAuth && !username.value) {
    next('/login')
  } else if (to.path === '/login' && username.value) {
    next('/')
  } else {
    next()
  }
})

export default router
